Hibernate +Spring Data JPA + Spring Boot+ Thymeleaf + Junit 懒加载问题

在做junit这种非web容器使用的时候,出现如下错误

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: ......., no session or session was closed

解决办法:

添加事务配置注解。junit代码如下:

@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
@Transactional
public class ArticleServiceImplTest{

@Test
public void test() {

}

}

完美解决问题,真开心

2.在web容器中,如果出现如下错误:

org.hibernate.LazyInitializationException: could not initialize proxy - no Session at

解决办法:
在web.xml中使用一个filter,放在 servlet 配置的后面,代码如下:

<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:META-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

3.如果使用了json化entity bean的功能,可能会出现如下错误:

No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer。。。

因为序列化对象A时,需要把里面的多对一关系的B拿出来,而B里面又有A的集合,如此反复,便报这样的错了

解决办法:
在entity bean 中使用 @JsonIgnore 注解

@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "role_id")
@JsonIgnore
private Role role;


-------------本文结束感谢您的阅读-------------
0%